package pikes.peak;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import org.springframework.web.servlet.support.RequestContext;

import pikes.html.xhtml.Flow;
import pikes.html.xhtml.table.TD;
import pikes.html.xhtml.table.TH;
import pikes.html.xhtml.table.TableCell;
import pikes.util.Util;

public class Cell implements RequestProperty<TableCell> {

	private Collection<Component> components = new LinkedList<Component>();

	private CellDecorator cellDecorator = CellDecorator.NULL_DECORATOR;

	private boolean isHeader = false;

	public Cell() {

	}

	public Cell(final boolean isHeader) {
		this.isHeader = isHeader;
	}

	public Cell(final Component component) {
		this(component, CellDecorator.NULL_DECORATOR);
	}

	public Cell(final boolean isHeader, final Component component) {
		this(isHeader, component, CellDecorator.NULL_DECORATOR);
	}

	public Cell(final Component component, final CellDecorator cellDecorator) {
		this(new Component[] { component }, cellDecorator);
	}

	public Cell(final boolean isHeader, final Component component, final CellDecorator cellDecorator) {
		this(isHeader, new Component[] { component }, cellDecorator);
	}

	public Cell(final Component[] components) {
		this(components, CellDecorator.NULL_DECORATOR);
	}

	public Cell(final boolean isHeader, final Component[] components) {
		this(isHeader, components, CellDecorator.NULL_DECORATOR);
	}

	public Cell(final Component[] components, final CellDecorator cellDecorator) {
		this(false, components, cellDecorator);
	}

	public Cell(final boolean isHeader, final Component[] components, final CellDecorator cellDecorator) {
		this.isHeader = isHeader;
		if (components != null) {
			for (Component component : components) {
				if (component != null) {
					this.components.add(component);
				}
			}
		}
		this.cellDecorator = cellDecorator;
	}

	public final void add(Component component) {
		if (component != null) {
			components.add(component);
		}
	}

	public final TableCell getValue(Map model, RequestContext requestContext) throws Exception {

		if (!Util.isEmpty(components)) {
			Iterator<Component> iComponents = components.iterator();

			Component component = iComponents.next();

			Flow flow = component.createHtml(model, requestContext);
			if (flow != null) {
				TableCell tableCell = null;
				if (isHeader) {
					tableCell = new TH(flow);
				}
				else {
					tableCell = new TD(flow);
				}

				while (iComponents.hasNext()) {
					component = iComponents.next();
					flow = component.createHtml(model, requestContext);
					tableCell.add(flow);
				}

				cellDecorator.decorateCell(tableCell, model, requestContext);
				return tableCell;
			}

		}
		return null;
	}

}
